package com.cskaoyan.service.impl;

import com.cskaoyan.bean.Order;
import com.cskaoyan.bean.OrderGoods;
import com.cskaoyan.bean.admin.vo.DateTimeVo;
import com.cskaoyan.bean.admin.vo.GoodsStatisticsVo;
import com.cskaoyan.bean.admin.vo.GoodsStatisticsRowsVo;
import com.cskaoyan.mapper.OrderGoodsMapper;
import com.cskaoyan.mapper.OrderMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.service.OrderGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderGoodsServiceImpl implements OrderGoodsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    public GoodsStatisticsVo selectGoodsStatistics() {
        //订单总量

        String[] strings = new String[5];
        strings[0] = "day";
        strings[1] = "orders";
        strings[3] = "products";
        strings[4] = "amount";
        
        //日期分组
        List<DateTimeVo> dateTimeVos = orderMapper.selectOrderGroupByTime();
        List<GoodsStatisticsRowsVo> goodsStatisticsRowsVos = new ArrayList<>();
        for (DateTimeVo dateTimeVo : dateTimeVos) {
            Date add_time = dateTimeVo.getAdd_time();
            List<Order> orders = orderMapper.selectPriceGroupByTime(add_time);
            //下单量
            Integer orderTotal = orders.size();
            //总金额
            Double a = 0.0 ;
            BigDecimal amount = new BigDecimal(a);
            //货品数量
            Short number = 0;
            for (Order order : orders) {
                BigDecimal goodsPrice = order.getGoodsPrice();
                amount = amount.add(goodsPrice);
                Integer id = order.getId();
                List<OrderGoods> numbers = orderGoodsMapper.selectNumberByOrderId(id);
                if (numbers != null){
                    for (OrderGoods orderGoods : numbers) {
                        Short number1 = orderGoods.getNumber();
                        number = (short)(number + number1);
                    }
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = simpleDateFormat.format(add_time);
            goodsStatisticsRowsVos.add(new GoodsStatisticsRowsVo(amount , orderTotal , time , number));
        }

        GoodsStatisticsVo goodsStatisticsVo = new GoodsStatisticsVo(strings, goodsStatisticsRowsVos);

        return goodsStatisticsVo;
    }
}
